package data.platform.timescale.internal.query;

import data.platform.common.service.query.RulePointQueryService;
import data.platform.common.stream.aggregates.RulePoint;
import data.platform.common.util.DateUtil;
import data.platform.timescale.persistence.repository.TsRulePointRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;

@ConditionalOnBean(name = "timeScaleConfig")
@Service
@Slf4j
@RequiredArgsConstructor
public class TsRulePointQueryServiceImpl implements RulePointQueryService {

    final TsRulePointRepository tsRulePointRepository;

    @Override
    public Flux<RulePoint> query(LocalDateTime beginTime, LocalDateTime endTime, String ruleId) {
        return tsRulePointRepository.queryRulePointEO(ruleId, DateUtil.getDateOfLocalDateTime(beginTime),
                DateUtil.getDateOfLocalDateTime(endTime))
                .map(rulePointEO -> {
                    RulePoint rulePoint = new RulePoint();
                    rulePoint.setRuleId(rulePointEO.getRuleId());
                    rulePoint.setEventTime(DateUtil.getDateTimeOfDate(rulePointEO.getEventTime()));
                    rulePoint.setHitNumber(rulePointEO.getHitNumber());
                    rulePoint.setHitData(rulePointEO.getHitData());
                    return rulePoint;
                });
    }
}
